package com.example.demo.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@Component
public class JwtUtils {

    private final static String JWT_SECRET = "123456";

    @Autowired
    private Environment env;


    public static String generateToken(long expireTime,String account) {
        JwtBuilder jwtBuilder = Jwts.builder();
        String jwt = jwtBuilder
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setId(UUID.randomUUID().toString())
                .setIssuedAt(new Date())
                .setSubject(account)
                .setExpiration(new Date(System.currentTimeMillis() + expireTime))
                .signWith(SignatureAlgorithm.HS256, JWT_SECRET)
                .compact();
        return jwt;

    }

    public static Claims parseToken(String jwt) {
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(JWT_SECRET).parseClaimsJws(jwt);
            Claims playload = claimsJws.getBody();
            return playload;

    }

    public static String getUsername(String jwt) {
        return parseToken(jwt).getSubject();
    }


    public void sendErrorResponse(HttpServletResponse response, int status, String message)  {
      try {
//          判断是 dev 环境还是 pro环境，区分 Access-Control-Allow-Origin
          String origin = env.acceptsProfiles("dev") ? "http://localhost:3010" : "http://zeus.sensetime.com:8083";
          response.setHeader("Access-Control-Allow-Origin", origin);
          response.setHeader("Access-Control-Allow-Credentials", "true");
          response.setStatus(status);
          response.setContentType(MediaType.APPLICATION_JSON_VALUE);
          response.setCharacterEncoding("UTF-8");
          Result errorResponse = new Result(status, message);
          response.getWriter().write(new ObjectMapper().writeValueAsString(errorResponse));
      }catch (IOException e){
          e.printStackTrace();
      }

    }
}
